package com.tal.pad.orc.base.net;

import okhttp3.Dispatcher;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;

import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 提供OkHttp的单例实例，以及针对线程池做优化;
 *
 * 注意：
 * 1. OKHttp 尽量使用单例；
 * 2. 如果有特殊的配置需求，尽量使用此类
 */
public class OkHttpClientHelper {

    private static final OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .dispatcher(getDefaultDispatcher())
            .protocols(Collections.unmodifiableList(Arrays.asList(Protocol.HTTP_1_1, Protocol.HTTP_2)))
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build();

    public static OkHttpClient getOkHttpClient(){
        return okHttpClient;
    }

    private static ExecutorService executorService = null;

    /**
     * 使用此Dispatcher,能复用线程池;
     */
    public synchronized static Dispatcher getDefaultDispatcher() {
        //TODO 暂时仍然使用OKHttp 自带的线程池.
        Dispatcher dispatcher = new Dispatcher(executorService);
        executorService = dispatcher.executorService();
        return dispatcher;
        //切换到自定义的线程池.（主要低性能设备需要重新评估影响）
//        return new Dispatcher(ThreadPoolExecutorUtil.getLightThreadPoolExecutor());
    }

}
